import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by yan_my on 2016/10/30.
 */
public class shrinkImage {
    private String srcpath;
    private String newpath;
    private BufferedImage originimage;
    private BufferedImage newimage;
    private int times;
    private int width;
    private int height;
    private int newwidth;
    private int newheight;
    private int[][]imageArray;
    private int[][]newimageArray;

    public shrinkImage(String srcpath,String newpath,int times )
    {
        this.srcpath=srcpath;
        this.newpath=newpath;
        this.times=times;
        try{
            this.originimage= ImageIO.read(new File(srcpath));
        }catch (IOException e){
            e.printStackTrace();
        }
        this.width=originimage.getWidth();
        this.height=originimage.getHeight();
        this.imageArray=new int[width][height];
        this.newwidth=width/times;
        this.newheight=height/times;
        this.newimageArray=new int[newwidth][newheight];
    }

    public void shrink()
    {
        for(int i=0;i<width;i++)
        {
            for(int j=0;j<height;j++)
            {
                imageArray[i][j]=originimage.getRGB(i,j);
            }
        }
        newimage=new BufferedImage(newwidth,newheight,BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<newwidth;i++)
        {
            double srcRow=i*times;
            int x=(int)srcRow;
            double t=srcRow-x;
            for(int j=0;j<newheight;j++)
            {
                double srcCol=j*times;
                int y=(int)srcCol;
                double u=srcCol-y;
                double coff1=(1.0d-t)*(1.0d-u);
                double coff2=(t)*(1.0d-u);
                double coff3=t*u;
                double coff4=(1.0d-t)*u;
                int m=x+1;
                int n=y+1;
                if(m>=width)
                    m--;
                if(n>=height)
                    n--;
                newimageArray[i][j]=(int)(coff1*imageArray[x][y])+(int)(coff2*imageArray[x][n])+(int)(coff3*imageArray[m][y])+(int)(coff4*imageArray[m][n]);
            }
        }

        for(int i=0;i<newwidth;i++) {
            for (int j = 0; j < newheight; j++)
            {
                newimage.setRGB(i,j,newimageArray[i][j]);
            }
        }

        try
        {
            File outfile=new File(newpath);
            ImageIO.write(newimage,"jpg",outfile);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
